<template>
    <div class="posts">
        <div class="postItem" v-for="(item, index) in postsList" :key="index">
            <!-- 用户信息盒子 -->
            <div class="user-info">
                <div class="user-img">
                    <img :src="item.userInfo.avatar" alt="">
                </div>
                <div class="user-username">
                    <span>{{ item.userInfo.username }}</span>
                </div>

                <el-button>+关注</el-button>
            </div>
            <!-- 标题 -->
            <div class="post-title" @click=ToPostDetail(item.id)>
                {{ item.title }}
            </div>
            <!-- 贴子内容 -->
            <div class="post-content">
                <div v-if="getContentImages(item.content).length > 0" class="post-img"
                    @click="showImagePreview(getContentImages(item.content), 0)">
                    <div class="post-imgItem">
                        <img :src="getContentImages(item.content)[0]" alt="">
                        <div class="image-count">
                            <el-icon>
                                <Picture />
                            </el-icon>
                            <span>{{ getContentImages(item.content).length }}</span>
                        </div>
                    </div>
                </div>
                <div class="sector" v-if="item.sector != null ">
                    <div class="sector-item">#{{ item.sector }}</div>
                </div>

                <div class="time">
                    <span>发布时间：</span>{{ formatDate(item.createTime) }}
                </div>
            </div>
        </div>
    </div>
    <template>
        <el-image-viewer v-if="previewVisible" :url-list="previewImages" v-model:initial-index="previewIndex"
            @close="previewVisible = false" teleported :z-index="2000" />
    </template>
    <LoadMoreTrigger ref="loadMoreRef" @load-more="PostItem" :loading="loading" :hasMore="hasMore" text="正在加载更多帖子..."
        noMoreText="已经到底啦~" />
</template>

<script setup>
import { ref, onMounted} from 'vue';
import { useRouter } from 'vue-router'; // 添加这行
import service from '@/utils/request';
import { Picture } from '@element-plus/icons-vue'
import { ElImageViewer } from 'element-plus'
import { formatDate } from '@/utils/date'
import DOMPurify from 'dompurify'
import LoadMoreTrigger from '@/components/LoadMoreTrigger.vue'

// Add loading ref
const loading = ref(false);
const hasMore = ref(true);
const postsList = ref([]);
const router = useRouter();
const page = ref({
    current: 1,
    size: 5
})
const previewImages = ref([])
const previewVisible = ref(false)
const previewIndex = ref(0)
const loadMoreRef = ref(null) // 新增元素引用

onMounted(() => {
    PostItem();
})


// Update PostItem function
const PostItem = async () => {
    try {
        loading.value = true;
        const res = await service.get('/posts/getAllPost', {
            params: {
                current: page.value.current,
                size: page.value.size
            }
        });
        if (res.code === 200) {
            hasMore.value = res.data.records.length >= page.value.size;
            postsList.value = res.data.records;
            console.log(res);

        }
    } finally {
        loading.value = false;
    }
}

// 前往详情贴子
const ToPostDetail = (id) => {
    router.push({ path: `/PostDetail/${id}` })
}

// 新增内容图片解析方法
const getContentImages = (html) => {
    if (!html) return []
    const parser = new DOMParser()
    const doc = parser.parseFromString(html, 'text/html')
    return Array.from(doc.querySelectorAll('.custom-image-wrapper img')).map(img => img.src)
}

// 修改原有预览方法保持兼容
const showImagePreview = (images, index) => {
    console.log('Showing image preview:', images, 'at index:', index);
    previewImages.value = Array.isArray(images) ? images : [images];
    previewIndex.value = index;
    previewVisible.value = true;
}
</script>

<style lang="scss" scoped>
.Load-more {
    text-align: center;
    padding: 16px;
    margin: 20px 0;
    border-radius: 8px;
    color: #666;
    font-size: 14px;

    &.no-more {
        background: #e9ecef;
        color: #999;
        box-shadow: none;
    }
}

.posts {
    max-width: 650px;
    margin: 0 auto;
    padding: 15px;
}

.postItem {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    padding: 20px;
    transition: all 0.3s ease;

    &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
}

.user-info {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .user-img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 12px;

        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }

    .user-username {
        font-weight: 500;
        margin-right: auto;
    }

    .el-button {
        padding: 6px 12px;
        font-size: 12px;
    }
}

.post-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    color: #333;

    &:hover {
        color: rgba(30, 181, 181);
        cursor: pointer;
    }
}

.post-content {

    // 新增自定义图片容器样式
    :deep(.custom-image-wrapper) {
        margin: 12px 0;
        padding: 8px;
        border-radius: 8px;
        transition: all 0.3s ease;

        img {
            width: 100%;
            height: auto;
            border-radius: 4px;
            display: block;
            max-width: 600px; // 限制最大宽度
            margin: 0 auto; // 居中显示
        }
    }

    // 保持原有图片样式与新样式共存
    .post-img {
        width: 350px;
        cursor: pointer;
        overflow: hidden;
        margin-bottom: 12px;

        .post-imgItem {
            position: relative;

            img {
                width: 100%;
                // max-height: 450px;
                object-fit: cover;
                transition: transform 0.3s ease;
                border-radius: 6px;

            }

            .image-count {
                position: absolute;
                top: 10px;
                right: 10px;
                background: rgba(0, 0, 0, 0.5);
                color: white;
                padding: 4px 8px;
                border-radius: 20px;
                display: flex;
                align-items: center;
                gap: 4px;
                font-size: 12px;

                .el-icon {
                    font-size: 14px;
                }
            }
        }


    }

    .sector {
        margin:8px 0 8px 0;

        .sector-item {
            background: #f0f0f0;
            padding: 4px 8px;
            font-size: 12px;
            color: #666;
            display: inline-block;
            margin-right: 8px;
        }
    }

    .time {
        font-size: 12px;
        color: #999;
    }
}
</style>
